package main

import (
  "net"
  "strings"
  "strconv"
  "log"
)

const connBuffer = 256
const eot = 4

type Netting struct{
  c net.Conn
}

func (* Netting) sendLoop(out chan string, c net.Conn){
  for {
    /* wait to receive message on the channel */
    s := <- out
    log.Stdout("Sending: %s", s)
    /* add end character to the message */
    s += string(eot)
    /* write the message to the connection */
    n, e := c.Write(strings.Bytes(s))
    if e != nil {
      log.Stderr("Error Writing: " + e.String())
      c.Close()
      return
    }
    if n != 0 {
      log.Stdout("Sent " + strconv.Itoa(n) + " bytes" )
    }
  }
}

func (* Netting) receiveLoop(in chan string, c net.Conn){
  /* left overs from previous message: */
  var left string
  
  for {
    /* receive buffert */
    var b [connBuffer]byte
    /* wait until a message is received from the server */
    n, e := c.Read(&b)
    
    if e != nil {
      log.Stderr("Error reading: " + e.String())
      log.Stderr("Closing connection")
      c.Close()
      return
    } else if n < 0 {
      log.Stderr("Error: " + e.String())
    } else {
      ss := strings.SplitAfter(string(b[0:n]), string(eot), 0)
      for i := 0; i < len(ss); i++ {
        if strings.LastIndex(ss[i],string(eot)) < 0 {
          left += ss[i]
        } else {
          s := left + ss[i]
          s = s[0:len(s)-1]
          left = ""
          /* and put the message on the channel */
          log.Stdoutf("Received: %s, %d", s, n)
          in <- s
        }
      }
    }
  }
}
